//Document Object Model (DOM)
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

//DOM to XML Serialization
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

//Base imports
import java.net.*;
import java.io.*;
import java.util.*;

public class ActionHandler implements Runnable {
    
    private Engine engine;
    private Socket sin;
    private Socket sout;
    private int ID;
    private Document dom;
    private InputStream is;
    private OutputStream os;

    ActionHandler(Engine e, Socket sin, Socket sout, int ID) {
	this.engine = e;
	this.ID = ID;

	this.sin = sin;
	this.sout = sout;
    }

    public void run() {

	try {

	    /**
	     * Create GameClient/GameServer Connections
	     */
	    is = sin.getInputStream();
	    os = sout.getOutputStream();

	    /**
	     *
	     * Recieve Action From GameClient
	     *
	     */

	    /** Create document object model from XML parse */
	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	    DocumentBuilder db = dbf.newDocumentBuilder();
	    dom = db.parse(is);
	    is.close();
	    
	    /** Create Action object from DOM parse */
	    Action action = new Action(dom.getDocumentElement());
	    
	    /**
	     *
	     * Update GameState
	     *
	     */
	    engine.changeState(action);

	    /**
	     *
	     * Send GameState to GameClient
	     *
	     */
	    
	    /** Create GameState DOM of Engine */
	    dbf = DocumentBuilderFactory.newInstance();
	    db = dbf.newDocumentBuilder();
	    dom = db.newDocument();
	    Element rootEle = engine.toXmlElement(dom);                                                                 
	    dom.appendChild(rootEle);                                                                                     

	    /** Set XML Formatting */
	    OutputFormat format = new OutputFormat(dom);
	    format.setIndenting(true);

	    /** Transmit Serialized XML from GameState DOM */
	    XMLSerializer serializer = new XMLSerializer(os, format);
	    serializer.serialize(dom);
	    os.close();

	}catch(ParserConfigurationException pce) {
	    pce.printStackTrace();
	}catch(SAXException se) {
	    se.printStackTrace();
	}catch(IOException ioe) {
	    ioe.printStackTrace();
	}catch (Exception e) {
	    System.out.println(e);
	}

	finally {
	    
	    try {
		sin.close();
		sout.close();
	    }
	    catch (IOException e){}

	}

    }

}


